package com.example.shopdemo.controller.shop;

import com.example.shopdemo.dto.ShopDTO;
import com.example.shopdemo.dto.ShopExecution;
import com.example.shopdemo.entity.Area;
import com.example.shopdemo.entity.PersonInfo;
import com.example.shopdemo.entity.Shop;
import com.example.shopdemo.entity.ShopCategory;
import com.example.shopdemo.enums.ShopStateEnum;
import com.example.shopdemo.service.AreaServiceImpl;
import com.example.shopdemo.service.ShopCategoryServiceImpl;
import com.example.shopdemo.service.ShopServiceImpl;
import com.example.shopdemo.utils.CodeUtil;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-19
 **/
@Controller
@Slf4j
@RequestMapping("/shop")
public class ShopManagementController {


    @Autowired
    private ShopServiceImpl shopService;

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private AreaServiceImpl areaService;

    @Autowired
    private ShopCategoryServiceImpl shopCategoryService;

    @RequestMapping(value = "/registerShop",method = RequestMethod.POST,consumes = "multipart/form-data")
    @ResponseBody
    public Map<String,Object> registerShop(HttpServletRequest request,Shop shop,@RequestParam("file") MultipartFile shopImg,
                                           @RequestParam("verifyCodeActual")String verifyCodeActual) {
        Map<String,Object> modelMap = new HashMap<>();
        if(!CodeUtil.checkVerifyCode(verifyCodeActual,request)) {
            modelMap.put("success",false);
            modelMap.put("errMsg","验证码错误");
            return modelMap;
        }
        if(shopImg == null) {
            modelMap.put("success",false);
            modelMap.put("errMsg","上传照片不能为空");
        }
        if(shop!=null && shopImg!=null){
            //TODO 放入ownerId
            ShopExecution shopExecution = shopService.addShop(shop,shopImg);
            if(shopExecution.getState() == ShopStateEnum.CHECK.getKey()) {
                //若shop创建成功，则加入session中，作为权限使用
                modelMap.put("success",true);
                @SuppressWarnings("unchecked")
                List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shopList");
                if(shopList!=null && shopList.size()>0) {
                    shopList.add(shopExecution.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                } else {
                    shopList = new ArrayList<Shop>();
                    shopList.add(shopExecution.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                }
            } else{
                modelMap.put("success",false);
                modelMap.put("errMsg",shopExecution.getStateInfo());
            }

        } else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请输入店铺信息");
        }
        return modelMap;
    }

    @RequestMapping(value = "/getKaptchaImage",method = RequestMethod.GET)
    public void getKaptchaImage(HttpServletRequest request, HttpServletResponse response) throws Exception{
        response.setHeader("Pragma","No-cache");
        response.setHeader("Cache-Control","no-cache");
        response.setDateHeader("Expires",0);
        response.setContentType("image/jpeg");
        String capText = captchaProducer.createText();
        HttpSession session = request.getSession(true);
        session.setAttribute("_code",capText);
        log.info(capText);
        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi,"jpg",out);
        try{
            out.flush();
        }finally {
            out.close();
        }
    }

    @RequestMapping("/getShopInitInfo")
    @ResponseBody
    public Map<String,Object> getShopInitInfo(){
        Map<String,Object> modelMap = new HashMap<String,Object>();
        List<ShopCategory> shopCategoryList = shopCategoryService.queryShopCategory(new ShopCategory());
        List<Area> areaList = areaService.getAreaList();
        if(shopCategoryList!=null&&areaList!=null){
            modelMap.put("success",true);
            modelMap.put("areaList",areaList);
            modelMap.put("shopCategoryList",shopCategoryList);
        } else {
            modelMap.put("success",false);
            modelMap.put("errMsg","获取商品类别与地区信息有问题");
        }
        return modelMap;
    }

    @RequestMapping("/getShopById")
    @ResponseBody
    public Map<String,Object> getShopById(@RequestParam("shopId")Long shopId){
        Map<String,Object> modelMap = new HashMap<>();
        if(shopId!=null){
            ShopDTO shopDTO = shopService.getByShopId(shopId);
            List<Area> areaList = areaService.getAreaList();
            modelMap.put("shopDTO",shopDTO);
            modelMap.put("areaList",areaList);
            modelMap.put("success",true);
        } else{
            modelMap.put("success",false);
            modelMap.put("errMsg","empty shopId");
        }
        return modelMap;
    }

    @RequestMapping(value = "/modifyShop",method = RequestMethod.POST,consumes = "multipart/form-data")
    @ResponseBody
    public Map<String,Object> modifyShop(HttpServletRequest request,Shop shop,@RequestParam(value = "file",required=false) MultipartFile shopImg,
                                           @RequestParam("verifyCodeActual")String verifyCodeActual) {
        Map<String,Object> modelMap = new HashMap<>();
        if(!CodeUtil.checkVerifyCode(verifyCodeActual,request)) {
            modelMap.put("success",false);
            modelMap.put("errMsg","验证码错误");
            return modelMap;
        }
        if(shop!=null){
            //TODO 放入ownerId
            ShopExecution shopExecution = shopService.modifyShop(shop,shopImg);
            if(shopExecution.getState() == ShopStateEnum.SUCCESS.getKey()) {
                //若shop创建成功，则加入session中，作为权限使用
                modelMap.put("success",true);
                @SuppressWarnings("unchecked")
                List<Shop> shopList = (List<Shop>)request.getSession().getAttribute("shopList");
                if(shopList!=null && shopList.size()>0) {
                    shopList.add(shopExecution.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                } else {
                    shopList = new ArrayList<Shop>();
                    shopList.add(shopExecution.getShop());
                    request.getSession().setAttribute("shopList",shopList);
                }
            } else{
                modelMap.put("success",false);
                modelMap.put("errMsg",shopExecution.getStateInfo());
            }

        } else{
            modelMap.put("success",false);
            modelMap.put("errMsg","请选择店铺");
        }
        return modelMap;
    }

    @GetMapping("/getShopList")
    @ResponseBody
    public Map<String,Object> getShopList(HttpServletRequest request,@RequestParam("page")int page,@RequestParam("size")int size){
        Map<String,Object> modelMap = new HashMap<>();
        PersonInfo user = new PersonInfo();
        user.setUserId(1L);
        user.setName("xu");
        request.getSession().setAttribute("user",user);
        user =(PersonInfo)request.getSession().getAttribute("user");
        long ownerId = user.getUserId();
        Shop shopCondition = new Shop();
        shopCondition.setOwnerId(ownerId);
        try{
            ShopExecution shopExecution = shopService.getShopList(shopCondition,page,size);
            modelMap.put("shopList",shopExecution.getShopList());
            modelMap.put("user",user);
            modelMap.put("success",true);

        }catch(Exception e){
            modelMap.put("success",false);
            modelMap.put("errMsg",e.getMessage());
        }
        return modelMap;
    }

    @RequestMapping("/getShopManagement")
    @ResponseBody
    public Map<String,Object> getShopManagement(HttpServletRequest request,@RequestParam(value = "shopId",required = false)Long shopId){
        Map<String,Object> modelMap = new HashMap<>();
        if(shopId<=0){
            Object currentShopObj = request.getSession().getAttribute("currentShop");
            if(currentShopObj==null){
                modelMap.put("redirect",true);
                modelMap.put("url","/shop/shoplist");
            } else{
                Shop currentShop =(Shop) currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId",currentShop.getShopId());
            }

        } else{
            Shop currentShop = new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
            modelMap.put("shopId",shopId);
        }
        return modelMap;
    }


}




